<script setup>
import { ref } from 'vue';
import { getCodeLogin, getMsgCode } from '@/apis/user'
import {useUserStore} from '@/stores'
const store=useUserStore()

	const form=ref(null)
	//定义表单响应式数据
	const formData=ref({
		mobile:'',
		code:''
	})
	//控制倒计时
	const showCountDown=ref(false)
	const countText=ref('获取验证码')
	//获取倒计时
	const changeTimeup=()=>{
	  showCountDown.value=false
		countText.value="再次获取验证码"
	}
	
	//勾选我同意
	const isAgree=ref(false)
	//校验规则
	const rules={
		mobile:{
			rules:[
				{ required: true, errorMessage: '请输入手机号' },
				{ pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
			]
		},
		code:{
			rules:[
				{ required: true, errorMessage: '请输入短信验证码' },
				{ pattern: /^\d{6}$/, errorMessage: '验证码格式不正确' }
			]
		}
	}
	
	//发送验证码
	const sendMsgCode=async()=>{
    //校验手机号
		await form.value.validateField('mobile')
		const res=await getMsgCode({mobile:formData.value.mobile,type:'login'})
		showCountDown.value=true
	}

	//勾选框
	const changeAgree=()=>{
		isAgree.value=!isAgree.value	
	}
	
	//登录
	const onLogin=async()=>{
		if(!isAgree.value){
			return uni.showToast({
				title:'请勾选我同意',
				icon:"error"
			})
		}
		try{
			await form.value.validate()
			//发送短信验证码请求
			const res=await getCodeLogin(formData.value)
			//持久化用户信息
			store.setUserStore(res.data)
			//提示用户
			uni.showToast({
				title:'登录成功'
			})
			//跳转页面
			uni[store.openType]({
				url:store.redireUrl
			})
		}catch(e){
			console.log(e);
		}
	}
	

</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formData" :rules="rules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
				v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码" 
        placeholder-style="color: #C3C3C5"
				v-model="formData.code"
      />
		   <view class="text-button" v-if="showCountDown">
				  <uni-countdown :second=7 :showDay="false" :showHour="false" :showMinute="false" color="#16C2A3" @timeup="changeTimeup"></uni-countdown>秒后发送验证码
			 </view>
      <text v-else class="text-button" @click="sendMsgCode" >{{countText}}</text>
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" color="#16C2A3" @click="changeAgree"/>
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onLogin">登 录</button>
  </uni-forms>
</template>

<script>
export default {
  options: {
    styleIsolation: 'shared'
  }
}
</script>

<style lang="scss">
@import './styles.scss';
</style>